package com.wyu.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、判断上传的数据是否多端
        if(ServletFileUpload.isMultipartContent(request)){
            //创建FileItemFactory实现类
            FileItemFactory fileItemFactory =new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload servletFileUpload =new ServletFileUpload(fileItemFactory);
            //解析上传数据，得到每一个表单FileItem
            try {
                List<FileItem> list=servletFileUpload.parseRequest(request);
                for (FileItem fileItem:list){
                    if (fileItem.isFormField()){
                        //普通表单项
                        System.out.println("表单项的name属性值："+fileItem.getFieldName());
                        System.out.println("表单项的value属性值："+fileItem.getString("UTF-8"));

                    }else {
                        //上传文件
                        System.out.println("表单项的name属性值："+fileItem.getFieldName());
                        System.out.println("上传的文件名："+fileItem.getName());
                        fileItem.write(new File("D:\\JavaWeb\\CTCKGLXT\\web\\file\\"+fileItem.getName()));
                        request.setAttribute("message", "文件上传成功!");
                    }
                }
            } catch (Exception e) {
                request.setAttribute("message", "错误信息: " + e.getMessage());
            }
            getServletContext().getRequestDispatcher("/fileupload.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
